package zheezes.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class BeanUtil {
	public static final Object getByField(Object obj, String name)
			throws Exception {
		Object value = null;
		Class clazz = obj.getClass();
		Field field = clazz.getField(name);
		if (field != null) {
			value = field.get(obj);
		}
		return value;
	}

	public static final Object getByMethod(Object obj, String name)
			throws Exception {
		Object value = null;
		Class clazz = obj.getClass();
		Method get = clazz.getMethod("get"
				+ Character.toUpperCase(name.charAt(0)) + name.substring(1));
		if (get != null) {
			value = get.invoke(obj);
		}
		return value;
	}

	public static final Object get(Object obj, String name) throws Exception {
		Object value = null;
		try {
			value = getByField(obj, name);
		} catch (Exception fe) {
			try {
				value = getByMethod(obj, name);
			} catch (Exception me) {
				me.printStackTrace();
				throw new Exception();
			}
		}
		return value;
	}
}
